using System.Collections.Generic;
using System.Transactions;
using PetShop.BusinessEntities;
using PetShop.BusinessEntityManagers;

namespace PetShop.BusinessFacade
{
    public class OrderFacade
    {
        public int CreateOrder(OrderInfo order)
        {
            using (var ts = new TransactionScope(TransactionScopeOption.Required))
            {
                var obo = new OrderBO();
                int ret = obo.Insert(order);
                var inventory = new ItemBO();
                LineItemInfo[] orderLineItems = order.LineItems;
                List<InventoryItemInfo> inventoryItems = ConvertOrderItemsToInvetoryItem(orderLineItems);
                inventory.TakeStock(inventoryItems.ToArray());
                ts.Complete();
                return ret;
            }
        }

        public bool VerifyAvailability(string itemId, int cartItemQuantity)
        {
            var bo = new ItemBO();
            bool boIsThereEnoughInStock = bo.IsThereEnoughInStock(itemId, cartItemQuantity);
            return boIsThereEnoughInStock;
        }

        private static List<InventoryItemInfo> ConvertOrderItemsToInvetoryItem(IEnumerable<LineItemInfo> orderItems)
        {
            var inventoryItems = new List<InventoryItemInfo>();
            foreach (LineItemInfo item in orderItems)
            {
                var lineItem = new InventoryItemInfo(item.ItemId, item.Quantity);
                inventoryItems.Add(lineItem);
            }
            return inventoryItems;
        }
    }
}